class Item < ActiveRecord::Base
  belongs_to :brand
  belongs_to :category
  attr_accessor :new_brandname
  before_save :create_brand_from_name
  
  def create_brand_from_name
    create_brand(:brandname => new_brandname) unless new_brandname.blank?
  end
  
  validates_presence_of :name,:detail,:price,:quantity 
  validates_uniqueness_of :name 
  validates_numericality_of :price,:quantity 
  validate :price_should_be_at_least_1_cent
  validate :quantity_should_be_at_least_1
  validate :expire_date_should_after_bought_date
  validate :bought_date_should_before_today
  
  protected
    def price_should_be_at_least_1_cent
      errors.add(:price, 'should be at least 0.01') if price.nil? ||
	price < 0.01
    end
    
    def quantity_should_be_at_least_1
      errors.add(:quantity, 'should be at least 1') if quantity.nil? ||
        quantity < 1
    end
    
    def expire_date_should_after_bought_date
      errors.add(:expire_date, 'Your item has already been expired when you bought') if bought_date > expire_date
    end
    
    def bought_date_should_before_today
      #errors.add(:bought_date,'You cannot bought things from future') if bought_date < Time.
    end
end
